//
//  NSString+CBExtension.m
//  CBEmotionView
//
//  Created by ly on 8/21/13.
//  Copyright (c) 2013 ly. All rights reserved.
//

#import "NSString+CBExtension.h"
#import "NSArray+CBExtension.h"
#import "CHEmotionHelper.h"
#import "EMotionModel.h"
#import "CBRegularExpressionManager.h"
#import "WZTextAttachment.h"


@implementation NSString (CBExtension)

- (NSString *)replaceCharactersAtIndexes:(NSArray *)indexes withString:(NSString *)aString
{
    NSAssert(indexes != nil, @"%s: indexes 不可以为nil", __PRETTY_FUNCTION__);
    NSAssert(aString != nil, @"%s: aString 不可以为nil", __PRETTY_FUNCTION__);
    
    NSUInteger offset = 0;
    NSMutableString *raw = [self mutableCopy];
    
    NSInteger prevLength = 0;
    for(NSInteger i = 0; i < [indexes count]; i++)
    {

            NSRange range = [[indexes objectAtIndex:i] rangeValue];
            prevLength = range.length;
            
            range.location -= offset;
            [raw replaceCharactersInRange:range withString:aString];
            offset = offset + prevLength - [aString length];
    }
    return raw;
}


- (NSMutableAttributedString *)cookEmotionStringWithFont:(UIFont *)font textColor:(UIColor *)color
{
    // 使用正则表达式查找特殊字符的位置
    __block NSArray *itemIndexes = [CBRegularExpressionManager itemIndexesWithPattern:@"\\[([^\\[\\]]*)\\]" inString:self];
    
    __block NSArray *names = nil;
    __block NSString *newString = nil;
    __block NSArray *newRanges = nil;
    
    // 查找表情对应的字符串 并加载相应的表情图片到内存中
    names = [self itemsForPattern:@"\\[([^\\[\\]]*)\\]" captureGroupIndex:0];
    // 将 emotionString 中的特殊字符串替换为空格
    newString = [self replaceCharactersAtIndexes:itemIndexes withString:@""];
    
    // 新的表情的占位符的 range 数组
    newRanges = [itemIndexes offsetRangesInArrayBy:[@" " length]];
    
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:newString attributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:font}];
    for (int i = 0; i < names.count; i ++) {
        NSString *name = names[i];
        NSRange range = [newRanges[i] rangeValue];
        NSTextAttachment *atta = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
        atta.image = [self getEmotionForKey:name];
        atta.bounds = CGRectMake(0, font.descender, font.lineHeight, font.lineHeight);
        NSAttributedString *at = [NSAttributedString attributedStringWithAttachment:atta];
        [attr insertAttributedString:at atIndex:range.location];
    }
    return attr;
}

- (UIImage *)getEmotionForKey:(NSString *)key
{
    CHEmotionHelper *helper =[CHEmotionHelper sharedInstance];
    EMotionModel *model = [helper getFileNameByWord:key];
    
    
    if (model) {
        
        return [UIImage imageNamed:[NSString stringWithFormat:@"%@/%@",model.directory,model.png]];
    } else {
        return nil;
    }
}

@end
